<?php
if (! defined ( 'YLSNS_INSTALL' )) {
	exit ( 'Access Denied' );
}
require_once 'oper.php';
function str_parcate($cate, &$str_parcate, $startID = 0) {
	if (! $cate [$startID] ['cup'])
		return;
	foreach ( $cate as $key => $value ) {
		if ($value ['cup'] == $startID) {
			$str_parcate .= $value ['cid'] . ',';
			str_parcate ( $cate, $str_parcate, $value ['cid'] );
		}
	}
}
function str_subcate($cate, &$str_subcate, $startID = 0) {
	foreach ( $cate as $key => $value ) {
		if ($value ['cup'] == $startID) {
			$str_subcate .= $value ['cid'] . ',';
			str_subcate ( $cate, $str_subcate, $value ['cid'] );
		}
	}
}
function addS(&$array) {
	if (is_array ( $array )) {
		foreach ( $array as $key => $value ) {
			addS ( $array [$key] );
		}
	} elseif (is_string ( $array )) {
		$array = addslashes ( $array );
	}
}
function result($result = 1, $output = 1) {
	if ($result) {
		$text = ' ... <span class="blue">OK</span>';
		if (! $output) {
			return $text;
		}
		echo $text;
	} else {
		$text = ' ... <span class="red">Failed</span>';
		if (! $output) {
			return $text;
		}
		echo $text;
	}
}
function createtable($sql, $db_charset) {
	$db_charset = (strpos ( $db_charset, '-' ) === FALSE) ? $db_charset : str_replace ( '-', '', $db_charset );
	$type = strtoupper ( preg_replace ( "/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql ) );
	$type = in_array ( $type, array (
			"MYISAM",
			"HEAP" 
	) ) ? $type : "MYISAM";
	return preg_replace ( "/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql ) . (mysql_get_server_info () > "4.1" ? " ENGINE=$type DEFAULT CHARSET=$db_charset" : " TYPE=$type");
}
function getip() {
	if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
		$onlineip = $_SERVER ['HTTP_X_FORWARDED_FOR'];
	} elseif (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) {
		$onlineip = $_SERVER ['HTTP_CLIENT_IP'];
	} else {
		$onlineip = $_SERVER ['REMOTE_ADDR'];
	}
	$onlineip = preg_match ( '/[\d\.]{7,15}/', addslashes ( $onlineip ), $onlineipmatches );
	return $onlineipmatches [0] ? $onlineipmatches [0] : 'unknown';
}
function writable($var) {
	$writeable = FALSE;
	$var = YLSNS . $var;
	if (! is_dir ( $var )) {
		@mkdir ( $var, 0777 );
	}
	if (is_dir ( $var )) {
		$var .= '/temp.txt';
		if (($fp = @fopen ( $var, 'w' )) && (fwrite ( $fp, 'OceanX' ))) {
			fclose ( $fp );
			@unlink ( $var );
			$writeable = TRUE;
		}
	}
	return $writeable;
}
function PWriteFile($filename, $content, $mode = 'ab') {
	if (strpos ( $filename, '..' ) !== FALSE) {
		return FALSE;
	}
	$path = dirname ( $filename );
	if (! is_dir ( $path )) {
		if (! mkdir ( $path, 0777 )) {
			return FALSE;
		}
	}
	$fp = @ fopen ( $filename, $mode );
	if ($fp) {
		flock ( $fp, LOCK_EX );
		fwrite ( $fp, $content );
		fclose ( $fp );
		@ chmod ( $filename, 0777 );
		return TRUE;
	}
	return FALSE;
}

/*function dump($var, $echo = true, $label = null, $strict = true) {
	$label = ($label === null) ? '' : rtrim ( $label ) . ' ';
	if (! $strict) {
		if (ini_get ( 'html_errors' )) {
			$output = print_r ( $var, true );
			$output = '<pre style="text-align:left">' . $label . htmlspecialchars ( $output, ENT_QUOTES ) . '</pre>';
		} else {
			$output = $label . " : " . print_r ( $var, true );
		}
	} else {
		ob_start ();
		var_dump ( $var );
		$output = ob_get_clean ();
		if (! extension_loaded ( 'xdebug' )) {
			$output = preg_replace ( "/\]\=\>\n(\s+)/m", "] => ", $output );
			$output = '<pre style="text-align:left">' . $label . htmlspecialchars ( $output, ENT_QUOTES ) . '</pre>';
		}
	}
	if ($echo) {
		echo ($output);
		return null;
	} else
		return $output;
}*/

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;
	$key = md5($key ? $key : 'abc123456');
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function executeSqlFile($file,$stop = true,$db_charset = 'utf-8') {
	if (!is_readable($file)) {
		$error = array(
				'error_code' => 'SQL文件不可读',
				'error_sql'  => '',
		);
		return $error;
	}
	$fp = fopen($file, 'rb');
	$sql = fread($fp, filesize($file));
	fclose($fp);
	$sql = str_replace("\r", "\n", $sql);
	foreach (explode(";\n", trim($sql)) as $query) {
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				//预处理建表语句
				$db_charset = (strpos($db_charset, '-') === FALSE) ? $db_charset : str_replace('-', '', $db_charset);
				$type   = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $query));
				$type   = in_array($type, array("MYISAM", "HEAP")) ? $type : "MYISAM";
				$_temp_query = preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $query).
				(mysql_get_server_info() > "4.1" ? " ENGINE=$type DEFAULT CHARSET=$db_charset" : " TYPE=$type");
				$res = mysql_query($_temp_query);
			}else {
				$res = mysql_query($query);
			}
			if($res === false) {
				$error[] = array(
						'error_code' => mysql_error(),
						'error_sql'  => $query,
				);

				if($stop) return $error[0];
			}
		}
	}
	return $error;
}
/*function mk_dir($dir, $mode = 0777) {
	if (is_dir($dir) || @mkdir($dir, $mode))
		return true;
	if (!mk_dir(dirname($dir), $mode))
		return false;
	return @mkdir($dir, $mode);
}*/

function getTemplateName() {
    require_once '../ocean/Extend/Library/ORG/Io/Dir.class.php';
    $doc = new DOMDocument();
    $dirs = new Dir ('../Public/cms/template' );
    foreach ($dirs as $key => $value) {
        $dirss = new Dir($value['pathname']);
        foreach ($dirss as $keys => $values) {
            if ($values['filename'] == 'sitedata') {
                $doc->load($values['pathname'].'/sitedata.xml'); //读取xml文件
                $humans = $doc->getElementsByTagName( "sitetemplate" ); //取得sitetemplate标签的对象数组
                foreach( $humans as $human ) {
                    $name = $human->getElementsByTagName('name');
                    $nameValue = $name->item(0)->nodeValue;
                    $ds[$value['filename']] = $nameValue;
                }
            }
        }
    }
    return $ds;
}

function readNodeXml($path) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "nodelist" );
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        M('cms_category')->add($headline);
    }
}

function readSiteXml($path) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "siteconfig" );
    $sid = 0;
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        $sid = $headline['siteid'];
        M('cms_site')->add($headline);
    }
    return $sid;
}

function addSystemConfig($path, $sid) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "siteOutherConfig" );
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        unset($headline['#text']);
        $arr['site-'.$sid] = $headline;
        model('Data')->lput('cmsconfig', $arr);
    }
}

function readTemplateXml($path) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "templatelist" );
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        M('cms_templates')->add($headline);
    }
}

function readContentXml($path) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "contentlist" );
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        M('cms_article')->add($headline);
    }
}

function readGroupXml($path) {
    $doc = new DOMDocument();
    $doc->load($path);
    $nodeList = $doc->getElementsByTagName( "grouplist" );
    foreach( $nodeList as $node ) {
        $headline = array();
        if ($node->childNodes->length) {
            foreach ($node->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }
        M('cms_group')->add($headline);
    }
}

function getSiteInfo($sid) {
    $findSite = M('cms_site')->where('siteid='.$sid)->find();
    $findSite['dirname'] = trim($findSite['dirname']);
    $dirname = empty($findSite['dirname'])?'':$findSite['dirname'].'/';
    $templatePath = '../'.$dirname;
    return $templatePath;
}

function copyTemplateFile($templatePath, $path) {
    $dir = opendir($templatePath);
    @mkdir($path);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' ) && ($file != 'sitedata')) {
            if ( is_dir($templatePath . '/' . $file) ) {
                copyTemplateFile($templatePath . '/' . $file,$path . '/' . $file);
            } else {
                copy($templatePath . '/' . $file,$path . '/' . $file);
            }
        }
    }
    closedir($dir);
}
?>